<?php
namespace app\common\service;


use app\common\util\Util;
use think\Db;
use think\Model;

class ClassAlbumService extends BaseService
{


    /**
     *
     * 微信端: 获取班级相册列表 UID=0时，为后台复用
     * @param $sid
     * @param $uid
     * @param $class_id
     * @param $p
     * @param $pageSize
     * @return mixed
     */
    public function getClassAlbumList($sid, $uid, $class_id, $p, $pageSize){
        $list = db('class_album')
                ->field('id,classid,uid,album_name,add_time')
                ->where(['classid' => $class_id, 'sid' => $sid, 'status' => 1])
                ->order('add_time DESC')
                ->limit(($p - 1) * $pageSize, $pageSize)
                ->select();
        if($list){
            $userResourcesService = new UserResourcesService();
            foreach($list as $k => $v){
                $list[$k]['add_time'] = date('Y-m-d', $v['add_time']);

                //获取相册图片总数
                $img_where = ['sid' => $sid, 'class_album_id' => $v['id'], 'status' => 1];
                $img_sum = db('class_album_img')
                            ->where($img_where)
                            ->count();
                $list[$k]['img_sum'] = $img_sum;

                //获取最新一张图片
                $latest_img = db('class_album_img')->field('user_resources_id')->where($img_where)->order('add_time DESC')->find();
                $list[$k]['latest_img_url'] = $userResourcesService->getUserResourcesUrl($sid, $uid, $latest_img['user_resources_id']);

                //获取相册创建者的头像
                $list[$k]['creater_headimgurl'] = db('user')->where(['user_id' => $v['uid']])->value('user_headimgurl');
            }
        }

        $album_count = $this->getClassAlbumCount($sid, $class_id);
        $data = [
            'album_count' => $album_count,
            'list' => $list
        ];
        return $data;
    }

    /**
     * 微信端: 新增或编辑相册信息
     * @param int $id
     * @param $sid
     * @param $uid
     * @param $class_id
     * @param $album_name
     * @return array
     * @throws \think\Exception
     */
    public function saveClassAlbum($id = 0, $sid, $uid, $class_id, $album_name){
        //查询用户是否为该班学员
        $class_students = db('class_students')->where(['sid' => $sid, 'uid' => $uid, 'classid' => $class_id])->find();
        if(!$class_students){
            return ['status' => 0, 'msg' => '无操作权限'];
        }

        $data = [
            'sid' => $sid,
            'uid' => $uid,
            'classid' => $class_id,
            'album_name' => $album_name,
            'add_time' => time()
        ];
        if($id > 0){
            //更新
            $info = db('class_album')->where(['sid' => $sid, 'album_name' => $album_name, 'status' => 1])->find();
            if($info){
                return ['status' => 0, 'msg' => '已存在相同名称的相册'];
            }
            $r = db('class_album')->where(['id' => $id])->update(['album_name' => $album_name, 'edit_time' => time()]);
        } else {
            //新增
            $r = db('class_album')->insert($data);
        }

        return $r == false ? ['status' => 0, 'msg' => '保存失败'] : ['status' => 1, 'msg' => '保存成功'];
    }


    /**
     * 微信端: 根据mediaId下载图片并保存至本地
     * @param $sid
     * @param $uid
     * @param $media_id
     * @param $class_album_id
     * @return array
     */
    public function uploadImgByMediaId($sid, $uid, $media_id, $class_id, $class_album_id){
        $wxService = new WeixinService();

        //保存路径
        $save_path = ROOT_PATH . 'public' . DS . 'uploads'. DS . 'class_album';
        if(!file_exists($save_path)){
            mkdir($save_path, 0777, true);
        }
        //文件命名
        $file_name = md5(date('YmdHis'));

        //调用下载接口并保存至相应地方
        $img_name = $wxService->download_temporary_media($sid, $media_id, $save_path, $file_name);

        //图片访问路径
        $img_url = $this->domain. DS .'uploads'. DS . 'class_album'. DS . $img_name;

        $userResourcesService = new UserResourcesService();
        $user_resources_id = $userResourcesService->addUserResources($sid, $uid, $save_path, $img_name, $img_url);

        if(!$user_resources_id){
            return ['status' => 0, 'msg' => '上传失败'];
        }

        //写入班级相册表
        $data = [
            'sid' => $sid,
            'uid' => $uid,
            'class_id' => $class_id,
            'class_album_id' => $class_album_id,
            'user_resources_id' => $user_resources_id,
            'add_time' => time()
        ];

        $r = db('class_album_img')->insert($data);
        if(!$r){
            return ['status' => 0, 'msg' => '上传异常'];
        }

        $d = ['img_url' => $userResourcesService->getUserResourcesUrl($sid, $uid, $user_resources_id)];
        return ['status' => 1, 'msg' => '上传成功', 'data' => $d];
    }


    /**
     * 微信端: 获取班级相册图片列表 UID=0代表后台请求
     * @param $sid
     * @param $class_album_id
     * @param $p
     * @param $pageSize
     * @return mixed
     */
    public function getClassAlbumImgList($sid, $uid, $class_id = 0, $class_album_id = 0, $p, $pageSize){
        $where = [
            'sid' => $sid,
            'status' => 1
        ];
        if($class_album_id > 0){
            //根据相册获取图片
            $where['class_album_id'] = $class_album_id;
        } else {
            //获取所有相册图片
            $where['class_id'] = $class_id;
        }

        $field = $uid > 0 ? 'id as img_id,user_resources_id' : 'id as img_id,class_id,class_album_id,user_resources_id';

        $img_list = db('class_album_img')
                    ->field($field)
                    ->where($where)
                    ->order('add_time DESC')
                    ->limit(($p - 1) * $pageSize, $pageSize)
                    ->select();
        if($img_list){
            $userResourcesService = new UserResourcesService();
            foreach ($img_list as $k => $v) {
                $img_list[$k]['img_url'] = $userResourcesService->getUserResourcesUrl($sid, $uid, $v['user_resources_id']);
            }
        }

        if($uid == 0){
            //后台请求
            $count = db('class_album_img')->where($where)->count();
            $data = [
                'page' => ['count' => $count],
                'content' => $img_list
            ];
            return $data;
        } else {
            return $img_list;
        }

    }


    /**
     * 微信端: 获取相册总数
     * @param $sid
     * @return int|string
     */
    public function getClassAlbumCount($sid, $class_id){
        return db('class_album')->where(['sid' => $sid, 'classid' => $class_id, 'status' => 1])->count();
    }


    /**
     * 后台: 删除相册
     * @param $sid
     * @param $class_album_id
     * @return array
     * @throws \think\Exception
     */
    public function deleteClassAlbum($sid, $class_album_id){
        // 启动事务
        Db::startTrans();

        $where = ['sid' => $sid, 'class_album_id' => $class_album_id, 'status' => 1];
        $update_data = ['edit_time' => time(), 'status' => -1];

        $imgs = db('class_album_img')->field('user_resources_id')->where($where)->select();
        if($imgs){
            foreach($imgs as $k => $v){
                $resouces_ids[$k] = $v['user_resources_id'];
            }
            //删除资源表
            $re = db('user_resources')->where(['id' => ['in', $resouces_ids], 'status' => 1])->setField('status', -1);

            //删除相册中的照片
            $r = db('class_album_img')->where($where)->update($update_data);

            if(!$r || !$re ){
                Db::rollback();
                return ['status' => 0, 'msg' => '删除失败！'];
            }
        }

        //删除相册
        $res = db('class_album')->where(['sid' => $sid, 'id' => $class_album_id, 'status' => 1])->update($update_data);
        if(!$res){
            Db::rollback();
            return ['status' => 0, 'msg' => '删除失败'];
        }

        //提交事务
        Db::commit();
        return ['status' => 1, 'msg' => '删除成功'];
    }


    /**
     * 后台: 删除班级相册图片
     * @param $sid
     * @param $img_id
     * @param int $is_batch
     * @return array
     * @throws \think\Exception
     */
    public function deleteClassAlbumImg($sid, $img_id, $is_batch = 0){
        Db::startTrans();
        $where = [
            'sid' => $sid,
            'id' => $is_batch == 0 ? $img_id : ['in', $img_id]
        ];
        $r = db('class_album_img')->where($where)->update(['edit_time' => time(), 'status' => -1]);

        if($is_batch){
            $resources = db('class_album_img')->field('user_resources_id')->where($where)->select();
            foreach($resources as $k => $v){
                $resources_ids[$k] = $v['user_resources_id'];
            }
            $res = db('user_resources')->where(['id' => ['in', $resources_ids], 'status' => 1])->setField('status', -1);
        } else {
            $resources_id = db('class_album_img')->where($where)->value('user_resources_id');
            $res = db('user_resources')->where(['id' => $resources_id, 'status' => 1])->setField('status', -1);
        }

        if(!$r || !$res){
            Db::rollback();
            return ['status' => 0, 'msg' => '删除失败'];
        }

        Db::commit();
        return ['status' => 1, 'msg' => '删除成功'];
    }
}